package com.enjoy.prepare.serial;

import org.junit.Test;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 类说明：测试JDK的序列化机制
 */
public class TestSerial {
    public static void main(String[] args) {


    }

    @Test
    public void test1() {
        // 创建一个User对象
        UserInfo user = new UserInfo("Mark", "123456");
        // 创建一个List对象
        List<String> list = new ArrayList<>();
        list.add("My name");
        list.add(" is");
        list.add(" Mark");
        try {
            ObjectOutputStream os = new ObjectOutputStream(Files.newOutputStream(Paths.get("E:/tmp/Serial.txt")));
            os.writeObject(user);// 将User对象写进文件
            os.writeObject(list);// 将List列表写进文件
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test2() {
        try {
            ObjectInputStream is = new ObjectInputStream(Files.newInputStream(Paths.get("E:/tmp/Serial.txt")));
            UserInfo temp = (UserInfo) is.readObject();// 从流中读取User的数据
            System.out.println(temp.getPhone());
            System.out.println(temp.getName());
            List tempList = (List) is.readObject();// 从流中读取List的数据
            for (Object o : tempList) {
                System.out.print(o);
            }
            is.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
